import { deleteMenuByIds, queryMenuTree, updateMenu } from "@/api/system/menu";
import { Menu } from "@/types/system/menu";
import { message } from "antd";
import { useState, useCallback, useEffect } from "react";

/**
 * 格式化菜单树
 * @param menu 
 * @returns 
 */
function cleanMenu(menu: Menu[]) {
    const flatArray: Menu[] = [];
    menu.forEach((node) => {
        const newNode: Menu = { ...node, children: undefined };
        if (node.children && node.children.length) {
            newNode.children = cleanMenu(node.children);
        }
        flatArray.push(newNode);
    });
    return flatArray;
}
function getIds(menu: Menu[]) {
    let flatArray: string[] = [];
    menu.forEach((node) => {
        flatArray.push(node.id||'')
        if (node.children && node.children.length) {
            flatArray = [...flatArray, ...getIds(node.children)];
        }
    });
    return flatArray;
}

export const useMenuTree = () => {
    const [messageApi] = message.useMessage();
    const [loading, setLoading] = useState(false);
    const [tableData, setTableData] = useState<Menu[]>([]);
    /**
     * 获取标签列表
     */
    const getMenuList = useCallback(async () => {
        setLoading(true);

        const res = await queryMenuTree();
        setLoading(false);
        if (res.code === 200) {
            setTableData(cleanMenu(res.data || []));
        }
    }, []);
    /**
     * @param row 更改状态
     */
    const changeStatus = async (row: Menu) => {
        await updateMenu({
            ...row,
            status: row.status === "0" ? "1" : "0",
        });
        getMenuList()
    };
    const removeMenu = async (row: Menu) => {
        const ids = getIds([row])
        setLoading(true)
        const res = await deleteMenuByIds({
            ids
        })
        setLoading(false)
        if (res.code == 200) {
            messageApi.success('删除成功!')
            getMenuList()
        }
    }

    useEffect(() => {
        getMenuList();
    }, [getMenuList]);
    return {
        loading,
        tableData,
        changeStatus,
        removeMenu,
        getMenuList
    }
}